// components/article/article-index.js
const { api } = require('../../../utils/api');

Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    bannerList: [
      {
        imageUrl: 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=800&auto=format&fit=crop&q=60'
      },
      {
        imageUrl: 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=800&auto=format&fit=crop&q=60'
      }
    ],
    provinceSelector: {
      showDialog: false,
      type: '科技特长生', //赛事推荐/最新资讯
      kjtcsProvince: "全部", // 默认选中"全部"
      sstjProvince: "",
      zxzxProvince: "",
      list: [
        "全部", "全国通用", "上海",
        "广东", "江苏", "北京",
        "浙江", "河北", "四川",
        "福建", "湖北", "湖南",
        "山东", "贵州", "新疆",
        "安徽", "重庆", "甘肃",
        "广西", "海南", "黑龙江",
        "吉林", "江西", "辽宁",
        "宁夏", "青海", "天津",
        "云南"
      ],
      selected: '全部',
      buttons: [
        {
          type: 'default',
          className: '',
          text: '关闭',
          value: 0
        },
        {
          type: 'primary',
          className: '',
          text: '确定',
          value: 1
        }
      ]
    },
    isPickerActive: false,
    provinceList: ['全部地区', '科技竞赛', '编程教育', '机器人教育'],
    typeList: ['全部资讯', '科技特长生', '赛事推荐', '最新资讯'],
    provinceIndex: 0,
    typeIndex: 0,
    articleList: [],
    isRefreshing: false, // 是否正在刷新
    pagination: {
      pageNo: 1,
      pageSize: 10,
      total: 0,
      hasMore: true
    }
  },

  /**
   * 组件生命周期函数
   */
  lifetimes: {
    attached () {
      // 组件加载时获取文章列表
      this.fetchArticleList();
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 获取文章列表
    async fetchArticleList(isLoadMore = false) {
      try {
        let city = "全部";
        if (this.data.provinceSelector.type === "科技特长生") {
          city = this.data.provinceSelector.kjtcsProvince;
        } else if (this.data.provinceSelector.type === "赛事推荐") {
          city = this.data.provinceSelector.sstjProvince;
        } else if (this.data.provinceSelector.type === "最新资讯") {
          city = this.data.provinceSelector.zxzxProvince;
        }
        const params = {
          type: this.data.provinceSelector.type,
          city: city === "全部" ? null : city,
          pageNo: isLoadMore ? this.data.pagination.pageNo + 1 : 1,
          pageSize: this.data.pagination.pageSize
        };

        if (!isLoadMore) {
          this.setData({
            articleList: []
          });
        }

        const res = await api.get('/teaching/xiaochengxuArticle/getArticlesByType', params);
        if (res && res.result && res.result.records) {
          // 处理返回的数据，转换为组件需要的格式
          const newArticleList = res.result.records.map(item => ({
            id: item.id,
            title: item.title,
            coverUrl: item.coverUrl || 'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=800&auto=format&fit=crop&q=60',
            tags: item.articleLabel ? item.articleLabel.split(',') : [],
            content: item.content,
            createTime: item.createTime,
            city: item.city,
            type: item.type
          }));

          // 更新分页信息
          const pagination = {
            pageNo: params.pageNo,
            pageSize: params.pageSize,
            total: res.result.total,
            hasMore: newArticleList.length === params.pageSize
          };

          // 合并文章列表
          const articleList = isLoadMore 
            ? [...this.data.articleList, ...newArticleList]
            : newArticleList;

          this.setData({
            articleList,
            pagination
          });
        }
      } catch (error) {
        console.error('获取文章列表失败：', error);
        wx.showToast({
          title: '获取文章列表失败',
          icon: 'none'
        });
      }
    },

    // 滚动到底部加载更多
    onScrollToLower() {
      if (this.data.pagination.hasMore) {
        this.fetchArticleList(true);
      }
    },

    onProvinceChange (e) {
      this.setData({
        provinceIndex: e.detail.value
      });
    },
    onTypeChange (e) {
      this.setData({
        typeIndex: e.detail.value
      });
    },
    onArticleTap (e) {
      const id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: `/pages/article/detail/article-detail?id=${id}`
      });
    },
    showProvinceSelector () {
      this.setData({
        'provinceSelector.showDialog': true
      });
    },
    showProvinceSelectorFor_kjtcs () {
      this.setData({
        'provinceSelector.type': '科技特长生',
        'provinceSelector.selected': this.data.provinceSelector.kjtcsProvince,
      });
      this.showProvinceSelector();
    },
    showProvinceSelectorFor_sstj () {
      this.setData({
        'provinceSelector.type': '赛事推荐',
        'provinceSelector.selected': this.data.provinceSelector.sstjProvince,
      });
      this.showProvinceSelector();
    },
    showProvinceSelectorFor_zxzx () {
      this.setData({
        'provinceSelector.type': '最新资讯',
        'provinceSelector.selected': this.data.provinceSelector.zxzxProvince,
      });
      this.showProvinceSelector();
    },
    hideProvinceSelector () {
      this.setData({
        'provinceSelector.showDialog': false
      });
    },
    selectProvince (e) {
      const province = e.currentTarget.dataset.province;
      if (this.data.provinceSelector.type === '科技特长生') {
        this.setData({
          'provinceSelector.kjtcsProvince': province,
          'provinceSelector.sstjProvince': "",
          'provinceSelector.zxzxProvince': ""
        });
      } else if (this.data.provinceSelector.type === '赛事推荐') {
        this.setData({
          'provinceSelector.kjtcsProvince': "",
          'provinceSelector.sstjProvince': province,
          'provinceSelector.zxzxProvince': ""
        });
      } else if (this.data.provinceSelector.type === '最新资讯') {
        this.setData({
          'provinceSelector.kjtcsProvince': "",
          'provinceSelector.sstjProvince': "",
          'provinceSelector.zxzxProvince': province
        });
      }
      this.hideProvinceSelector();
      this.fetchArticleList();
    },
    // 下拉刷新
    async onRefresh() {
      this.setData({ isRefreshing: true });
      await this.fetchArticleList();
      this.setData({ isRefreshing: false });
    }
  }
})